package com.token.handler;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.DES;
import com.alibaba.fastjson.JSON;
import com.token.domain.AjaxResult;
import com.token.task.VerifyTask;
import com.token.utils.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@Slf4j
@Component
public class OverallSituationInterceptor implements HandlerInterceptor {

    private static final DES des = new DES(Mode.CBC, Padding.PKCS5Padding, JWTUtil.APPLY_KEY.getBytes(), JWTUtil.DES_KEY.getBytes());
    private final List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 3, 5, 7));

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!VerifyTask.VerifyResultStr.equals("")) {
            String[] split = VerifyTask.VerifyResultStr.split(VerifyTask.split);
            switch (numbers.get(RandomUtil.randomInt(numbers.size()))) {
                case 1:
                    log.info("验证方法：1");
                    if (Integer.parseInt(des.decryptStr(split[1])) % 3 == 1) {
                        return true;
                    } else {
                        error(response);
                        return false;
                    }
                case 3:
                    log.info("验证方法：2");
                    if (Integer.parseInt(des.decryptStr(split[3])) % 4 == 2) {
                        return true;
                    } else {
                        error(response);
                        return false;
                    }
                case 5:
                    log.info("验证方法：3");
                    if (Integer.parseInt(des.decryptStr(split[5])) % 5 == 3) {
                        return true;
                    } else {
                        error(response);
                        return false;
                    }
                case 7:
                    log.info("验证方法：4");
                    if (Integer.parseInt(des.decryptStr(split[7])) % 6 == 4) {
                        return true;
                    } else {
                        error(response);
                        return false;
                    }
            }
            return true;
        } else {
            error(response);
            return false;
        }
    }

    private void error(HttpServletResponse response) throws IOException {
        response.setStatus(200);
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        response.getWriter().print(JSON.toJSONString(AjaxResult.error("缺少认证文件 或 认证文件无法使用")));
    }
}
